package repositories

import (
	"fmt"
	"github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/core/errors"
	"github.com/spf13/viper"
	"irisfarm/app/commons/auth"
	"irisfarm/app/services"
	"irisfarm/app/utils"
	"strconv"
	"time"
)

type AuthRepository struct {
}

// 登录
func (u *AuthRepository) Login(ctx iris.Context) (map[string]string, error) {
	// 获取用户信息
	authService := services.UserService{}
	userModel, err := authService.GetByUsername(ctx)
	if err != nil {
		return nil, err
	}

	// 进行登录验证
	if userModel.Username == ctx.PostValue("username") && userModel.Password == utils.Md5(ctx.PostValue("password")) {
		token := jwt.NewTokenWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
			"uid":         strconv.Itoa(int(userModel.ID)),
			"username":    string(userModel.Username),
			"time":        time.Now(),
			"expire_time": time.Hour * 24 * 30,
		})

		// Sign and get the complete encoded token as a string using the secret
		tokenString, err := token.SignedString([]byte(viper.GetString("app.key")))
		if err != nil {
			return nil, err
		}

		returnData := make(map[string]string)
		returnData["uid"] = strconv.Itoa(int(userModel.ID))
		returnData["username"] = userModel.Username
		returnData["token"] = tokenString

		return returnData, nil
	}
	return nil, errors.New("密码错误")
}

// 退出登录
func (u *AuthRepository) Logout(ctx iris.Context) (map[string]interface{}, error) {
	// 使用的jwt，没法退出登录，退出登录的时候不需要调用服务器接口
	user, _ := auth.User(ctx)
	fmt.Println(user.Username)

	returnData := make(map[string]interface{})

	returnData["username"] = user.Username
	returnData["uid"] = auth.Uid(ctx)
	returnData["check"] = auth.Check(ctx)

	return returnData, nil
}
